package model

import (
	"encoding/json"
	"github.com/gomodule/redigo/redis"
	"go_code/chatroom/server/message"
)

var UserDaoObj *UserDao

type UserDao struct {
	redisPool *redis.Pool
}

func NewUserDao(redisPool *redis.Pool) (userDao *UserDao) {
	userDao = &UserDao{
		redisPool: redisPool,
	}

	return
}

func (ud *UserDao) getUserById(conn redis.Conn, userId int64) (user *User, err error) {
	reply, err := redis.String(conn.Do("HGet", "users", userId))
	if err != nil {
		if err == redis.ErrNil {
			err = ErrUserNotExists
		}
		return
	}

	_ = json.Unmarshal([]byte(reply), &user)
	return
}

func (ud *UserDao) Register(registerMsg *message.RegisterReqMessage) (err error) {
	var user *message.User = &registerMsg.User
	conn := ud.redisPool.Get()
	defer func() {
		err = conn.Close()
		if err != nil {
			return 
		}
	}()

	_, err = ud.getUserById(conn, user.UserId)
	if err == nil {
		err = ErrUserExists
		return
	}

	err = ud.save(conn, user)

	return
}

func (ud *UserDao) save(conn redis.Conn, user *message.User) (err error) {
	marshal, _ := json.Marshal(user)
	_, _ = conn.Do("HSet", "users", user.UserId, string(marshal))

	return
}

func (ud *UserDao) Login(loginReq *message.LoginReqMessage) (user *User, err error) {
	conn := ud.redisPool.Get()
	defer func() {
		err = conn.Close()
		if err != nil {
			return
		}
	}()

	user, err = ud.getUserById(conn, loginReq.User.UserId)
	if err != nil {
		return
	}

	if user.Password != loginReq.User.Password {
		err = ErrPassword
		return
	}

	return
}


